<template>
    <a-modal v-model:open="showModal" :width="400" :title="formTitle" @ok="confirm">
        <div class="pt-[20px]" aria-hidden="true">
            <a-form :model="formData" ref="formRef" :label-col="{ style: { width: '80px' } }">
                <a-form-item label="名称" name="group_name" :rules="[{ required: true, message: '请输入分组名称' }]">
                    <a-input v-model:value="formData.group_name" />
                </a-form-item>
                <a-form-item label="排序" name="sort" :rules="[{ required: true, message: '排序' }]">
                    <a-input-number class="w-full" v-model:value="formData.sort" />
                </a-form-item>
            </a-form>
        </div>
    </a-modal>
</template>
<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { message } from 'ant-design-vue';
import { addFileGroup, editFileGroup } from '@/utils/api/file';

const showModal = ref<boolean>(false);

/**
 * 表单数据
 */
const initialFormData = {
    group_id: 0,
    type: 'image',
    group_name: '',
    sort: 100
}

const setFileType = (type: string) => {
    formData.type = type;
}

const formData: Record<string, any> = reactive({ ...initialFormData })

const formRef = ref();

const formTitle = ref('添加分组');

const setFormData = async (row: any = null) => {
    if (row == null) {
        formTitle.value = '添加分组';
        Object.assign(formData, initialFormData);
    } else {
        formTitle.value = '编辑分组';
        Object.assign(formData, row);
    }
}

const emit = defineEmits(['complete']);

const confirm = (e: MouseEvent) => {
    formRef.value
        .validate()
        .then(() => {
            console.log(formData);
            if (formData.group_id > 0) {
                editFileGroup(formData).then((res: any) => {
                    message.success(res.message)
                })
            }else{
                addFileGroup(formData).then((res: any) => {
                    message.success(res.message)
                })
            }
            showModal.value = false;
            setTimeout(function () {
                emit('complete');
            }, 1000);
        });
};



defineExpose({
    showModal,
    setFormData,
    setFileType
})
</script>